<!-- eslint-disable vue/this-in-template -->
<template>
  <div class="container">
    <div class="top">
      <el-form :model="warehouseParams" size="small" :inline="true" label-width="68px">
        <el-form-item :label="$t('component.index.warehouseNo')" prop="warehouseNo">
          <el-select v-model="warehouseParams.warehouseNo" :placeholder="$t('component.index.WarehousePlaceholder')" style="width: 240px">
            <el-option
              v-for="option in warehouseList"
              :key="option.warehouseNo"
              :label="option.warehouseNo"
              :value="option.warehouseNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getWarehouseList">{{$t('component.search')}}</el-button>
        </el-form-item>

      </el-form>
    </div>
    <div>
      <el-row :gutter="10" class="mb8">
        <right-toolbar @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <div class="top">
      <div v-for="item in imgList" :key="item.cargoType" class="img-item">
        <img :src="item.img" alt="">
        <span>{{ item.name }}</span>
      </div>
    </div>
    <div class="content" ref="rollBoxContainer" @mousewheel.prevent="rollingMainWindow"  :style="`height:${height}px;`" @mousedown="handleStartMove" @mousemove="handleMovingZoomElement" >
      <div class="level">
        <div v-for="item in warehouselayerZ" :key="item" class="level-item" :class="{active: activeIndex === item}" @click="handleChange(item)">
          {{ item }} {{$t('component.index.level')}}
        </div>
      </div>
      <div class="box"  :style="mainRollingStyle" ref="zoomElement" :draggable="false">
        <div v-for="(line, index) in list" :key="index" class="line" >
          <div v-for="(item) in line" :key="item.cargoNo" class="item" :class="{ full: item.cargoLocationStatus == 1 , lock: item.cargoLocationStatus == 2,out_order: item.cargoLocationStatus == 1&&taskType == 1,move_orderEnd:item.cargoLocationStatus == 0&&taskType == 2&&status=='end'}" @mouseover="mov" @mouseenter="mouthEnter(item,list)" @mouseleave="mouthLeave" @mousemove="stopTouch" @click="handleUpdate(item)" >
            <span v-if="item.cargoType === -1 && item.roadNo !== 0" class="roadno" aria-readonly="true">{{ item.roadNo }}</span>
            <img :src="getImg(item)" alt="" >
            <span v-if="item.cargoType === -1 && item.roadNo !== 0" class="roadline" aria-readonly="true">{{ item.roadLine }}</span>
          </div>
        </div>

      </div>
    </div>

    <div>
      <div v-if="isLayerVisible" class="overlay">
        <div class="content-overlay content">
          <div class="start-and-end">
            <h3>选择起点和终点</h3>
            <el-form-item label="起点货位">
              <el-input v-model="startDate" readonly style="width: 60px"/>
            </el-form-item>
            <el-form-item label="终点货位">
              <el-input v-model="endDate" readonly style="width: 60px"/>
            </el-form-item>
            <el-button @click="isLayerVisible = false">确认选择</el-button>
          </div>
          <div class="box"  :style="mainRollingStyle" ref="zoomElement" :draggable="false">
            <div v-for="(line, index) in list" :key="index" class="line" >
              <div v-for="(item) in line" :key="item.cargoNo" class="item" :class="{ full: item.cargoLocationStatus == 1 , lock: item.cargoLocationStatus == 2,out_order: item.cargoLocationStatus == 1&&taskType == 1,move_orderEnd:item.cargoLocationStatus == 0&&taskType == 2&&status=='end'}" @mouseover="mov" @mouseenter="mouthEnter(item,list)" @mouseleave="mouthLeave" @mousemove="stopTouch" @click="handleUpdate(item)" >
                <span v-if="item.cargoType === -1 && item.roadNo !== 0" class="roadno" aria-readonly="true">{{ item.roadNo }}</span>
                <img :src="getImg(item)" alt="" >
                <span v-if="item.cargoType === -1 && item.roadNo !== 0" class="roadline" aria-readonly="true">{{ item.roadLine }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改货位对话框 -->
    <el-dialog :title="$t('component.index.cargo.title')" v-model="update" width="500px">

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item :label="$t('component.index.cargo.cargoNo')" prop="cargoNo">
          <el-input v-model="form.cargoNo" :placeholder="$t('component.index.cargo.enterNo')" readonly />
        </el-form-item>
        <!-- <el-form-item label="{{$t('index.cargo.callNo')}}" prop="cargoName">
        <el-input v-model="form.cargoName" :placeholder="{{$t('index.cargo.enterCallNo')}}" />
        </el-form-item> -->
        <el-form-item v-if="form.cargoType === -1" :label="$t('component.index.cargo.area')" prop="areaId">
          <el-input v-model="form.areaId" :placeholder="$t('component.index.cargo.enterArea')" />
        </el-form-item>
        <el-form-item v-if="form.cargoType === -1" :label="$t('component.index.cargo.road')" prop="roadNo">
          <el-input v-model="form.roadNo" :placeholder="$t('component.index.cargo.enterRoad')"/>
        </el-form-item>
        <el-form-item v-if="form.cargoType === -1 && form.roadNo !== null" :label="$t('component.index.cargo.roadNo')" prop="roadLine">
          <el-input-number v-model="form.roadLine" controls-position="right" :min="1" />
        </el-form-item>
        <el-form-item v-if="form.cargoType === -1" :label="$t('component.index.cargo.warehouse')" prop="warehouse">
          <el-input v-model="form.warehouseNo" :placeholder="$t('component.index.cargo.enterWarehouse')" readonly />
        </el-form-item>
        <el-form-item v-if="form.cargoType === -1" :label="$t('component.index.cargo.pallet')" prop="palletNO">
          <el-input v-model="form.palletNo" :placeholder="$t('component.index.cargo.noPallet')" readonly />
        </el-form-item>
        <el-form-item :label="$t('component.index.cargo.type')">
          <el-select v-model="form.cargoType" :placeholder="$t('component.index.cargo.selectType')">
            <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('component.index.cargo.posX')" prop="posiX">
          <el-input v-model="form.posiX" :placeholder="$t('index.cargo.enterPosX')" readonly />
        </el-form-item>
        <el-form-item :label="$t('component.index.cargo.posY')" prop="posiY">
          <el-input v-model="form.posiY" :placeholder="$t('index.cargo.enterPosY')" readonly />
        </el-form-item>
        <el-form-item :label="$t('component.index.cargo.posZ')" prop="posiZ">
          <el-input v-model="form.posiZ" :placeholder="$t('component.index.cargo.enterPosZ')" readonly />
        </el-form-item>
        <el-form-item :label="$t('component.index.cargo.remark')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('component.index.cargo.enterRemark')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('component.index.cargo.confirm')}}</el-button>
        <el-button @click="cancel">{{$t('component.index.cargo.cancel')}}</el-button>
        <el-button type="warning" @click="runOutOrderTask">出库</el-button>
      </div>
    </el-dialog>
<!--    鼠标移过时出现的白色框-->
    <el-card class="box-card"  :style="cardStyle" v-if="getObjectProperties().length>0">
      <div v-for="prop in getObjectProperties()" :key="prop.name" class="info_card">
        <div><div class="card-label">{{ prop.name }}</div><span>{{prop.value===null?"无":prop.value}}</span></div>
      </div>
    </el-card>
    <el-button @click="outOrder">出库</el-button>
    <el-button @click="moveOrder">移库</el-button>
  </div>

</template>

<script>
// import { createRequire } from 'module';
// const require = createRequire(import.meta.url);
import zero from "@/assets/images/0.png";
import first from "@/assets/images/1.png";
import second from "@/assets/images/2.png";
import third from "@/assets/images/3.png";
import forth from "@/assets/images/4.png";
import fifth from "@/assets/images/5.png";
import six from "@/assets/images/6.png";
import cargo from "/public/resource/js/cargo.json"
import {
  list,
  deleteOne,
  batchDelete,
  getImportUrl,
  getExportUrl,
  getCargoList,
  getWarehouseList,
  addOutOrderTask,
  runningOutOrderTask
} from './workbench.api';
import { useI18n } from '/src/hooks/web/useI18n';

const {t} = useI18n()
export default {
  mounted() {
    this.zoomElement = this.$refs.zoomElement
    this.rollBoxContainer = this.$refs.rollBoxContainer
    window.addEventListener('mouseup', () => {
      this.startMove = false
    })
  },
  watch:{
    taskInfo: {
    		handler(newVal, oldVal) {
    			//todo
          if(newVal){
            this.taskType = 0
          }
    		},
    		immediate: true,
         	deep: true // 可以深度检测到 person 对象的属性值的变化
    	}
  },
  props: {
    height: {
      type: [Number, String],
      default: '100%',
    },
  },
  computed:{
    cardStyle(){
      return {
        position:`absolute`,
        top: `${this.cliendData.y-98}px`,
        left: `${this.cliendData.x-208}px`
      }
    },
    mainRollingStyle() {
      return {
        transformOrigin: `${this.mousePosition.x+50}px ${this.mousePosition.y}px`,
        transform: `scale(${this.mainCurScale})`,
        cursor: this.mainCurScale > 0.5 ? 'grab' : '',
      }
    },
    types(){
      return[
        {value: '' , label: t('component.index.type.select')},
        {value: -1, label: t('component.index.type.cargo')},
        {value: 1, label: t('component.index.type.ramp')},
        {value: 2, label: t('component.index.type.inlet')},
        {value: 3, label: t('component.index.type.outlet')},
        {value: 4, label: t('component.index.type.elevator')},
        {value: 5, label: t('component.index.type.pillar')},
        {value: 6, label: t('component.index.type.pile')},
        {value: 7, label: t('component.views_wms_cargo_index_13051') },
      ]
    },
    imgList(){
      return[
        {
          img: zero,
          cargoType: -1,
          name: t('component.index.type.cargo')
        },
        {
          img: first,
          cargoType: 1,
          name: t('component.index.type.ramp')
        },
        {
          img: first,
          cargoType: 7,
          name: t('component.index.type.ramp')
        },
        {
          img: second,
          cargoType: 2,
          name: t('component.index.type.inlet')
        },
        {
          img: third,
          cargoType: 3,
          name: t('component.index.type.outlet')
        },
        {
          img: forth,
          cargoType: 4,
          name: t('component.index.type.elevator')
        },
        {
          img: fifth,
          cargoType: 5,
          name: t('component.index.type.pillar')
        },
        {
          img: six,
          cargoType: 6,
          name: t('component.index.type.pile')
        }
      ]
    },
    // 表单校验
    rules(){
      return{
        cargoNo: [
          { required: true, message: t('component.index.rules.cargoNo'), trigger: "blur" }
        ],
        warehouse: [
          { required: true, message: t('component.index.rules.warehouse'), trigger: "blur" }
        ],
        cargoType: [
          { required: true, message: t('component.index.rules.cargoType'), trigger: "change" }
        ],
        posiX: [
          { required: true, message: t('component.index.rules.posiX'), trigger: "blur" }
        ],
        posiY: [
          { required: true, message: t('component.index.rules.posiY'), trigger: "blur" }
        ],
        posiZ: [
          { required: true, message: t('component.index.rules.posiZ'), trigger: "blur" }
        ],
      }
    }
  },
  data() {
    return {
      status:'',
      taskType:0,//1出库 2移库
      taskInfo:{},
      sameItemList:[],
      cliendData:{x:0,y:0},
      itemInfo:null,
      rollBoxContainer: null,
      zoomElement: null,
      redBox: null,
      mainCurScale: 1,
      mousePosition: { x: 0, y: 0 },
      calcMousePosition: { x: 0, y: 0 },
      startMove: false,
      activeIndex: 1,
      list: [],
      itemIndex : null,
      warehouseNo: '',
      warehouselayerZ: null,
      warehouselayerX: null,
      warehouselayerY: null,
      warehouseList: [],
      warehouseParams: {
        warehouseNo: null,
        warehouseName: null,
        layerX: null,
        layerY: null,
        layerZ: null
      },
      isLayerVisible: false,
      startDate: null,
      endDate: null,
      // 货位表格数据
      cargoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      update: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cargoNo: null,
        cargoName: null,
        areaId: null,
        roadNo: null,
        roadLine: null,
        warehouse: null,
        palletNo: null,
        cargoLocationStatus: null,
        cargoType: null,
        posiX: null,
        posiY: null,
        posiZ: null,
        createBy: null,
        updateBy: null,
      },
      // 表单参数
      form: {},

    }
  },
  created(){
    this.getWarehouseLista()


  },

  methods: {
    getWarehouseLista() {
      getWarehouseList(this.warehouseParams).then(response => {
        console.log(response)
        this.warehouselayerZ = response.layerZ
        this.warehouselayerX = response.layerX
        this.warehouselayerY = response.layerY
        this.warehouseList.push(response)
        console.log('warehouseList.layerZ==', this.warehouseList)
        this.getCargoLists()
      }).catch(error=>{
        console.log(error)
      })
    },
    getCargoLists(){
      var index = 1
      var X = this.warehouselayerX
      const params = Object.assign({}, {index}, {X: X})
      console.log(1,params)
      getCargoList(params).then(res=>{
        console.log(res);
        this.list = res
      })
    },
    getObjectProperties() {
      let properties = [];
      for (let key in this.itemInfo) {
        if (this.itemInfo.hasOwnProperty(key)) {
          properties.push({ name: key, value: this.itemInfo[key] });
        }
      }
      return properties;
    },
    mov(e){
      // console.log(e.target)
    },
    stopTouch(e){
      this.cliendData.x = e.clientX
      this.cliendData.y = e.clientY
    },
    clearItemInfo(){
      this.itemInfo = {}
      this.sameItemList = []
    },
    mouthLeave(){
      this.clearItemInfo()
    },
    mouthEnter(item,list){

      if (item.cargoType != -1){
        return
      }
      this.itemInfo = item
      for(let i of list){
        for (let j of i){
          if (j.roadNo == item.roadNo && j.roadLine!=item.roadLine){
            this.sameItemList.push(j)
          }
        }
      }
    },
    handleMovingZoomElement(e) {
      if (!this.startMove) {
        return
      }
      // console.log(this.mousePosition)
      const scale = this.mainCurScale
      const { movementX, movementY } = e
      if (this.mainCurScale < 1) {
        this.mousePosition.x += movementX / scale
        this.mousePosition.y += movementY / scale
      } else {
        this.mousePosition.x -= movementX / scale
        this.mousePosition.y -= movementY / scale
      }
      this.mousePosition = { ...this.mousePosition }
      this.synchronizeMoveRedBox()
    },
    handleStartMove() {
      this.startMove = true
    },
    getRect(el) {
      if (el) return el && el.getBoundingClientRect()
      else return {}
    },
    rollingMainWindow(e) {
      const { clientX, clientY } = e
      const delta = Math.sign(e.deltaY)
      let defaultCurScale = this.mainCurScale
      this.mainCurScale -= delta * 0.05
      this.mainCurScale = Math.max(this.mainCurScale, 0.2)
      const rollBoxRect = this.getRect(this.rollBoxContainer)

      const { left, top, width, height } = this.getRect(this.zoomElement)

      this.mousePosition.x = ((clientX - left) / width) * rollBoxRect.width
      this.mousePosition.y = ((clientY - top) / height) * rollBoxRect.height
      this.synchronizeMoveRedBox()
    },
    synchronizeMoveRedBox() {
      // console.log(this.rollBoxContainer)
      const rollBoxRect = this.getRect(this.rollBoxContainer)
      const { width, height } = this.getRect(this.smallWindow)
      this.calcMousePosition.x = (this.mousePosition.x / rollBoxRect.width) * width
      this.calcMousePosition.y = (this.mousePosition.y / rollBoxRect.height) * height
    },
    // 取消按钮
    cancel() {
      this.update = false;
      this.reset();
    },
    async runOutOrderTask(){
      //以货位编号为起点，添加出库任务
      const data = {
        taskType : 1,
        startNode : this.form.cargoNo
      }
      const taskNo = await addOutOrderTask(data)
      console.log(taskNo)
      //拿到返回的任务编号 根据任务编号执行任务
      const runningTaskData = {
        taskNo : taskNo
      }
      await runningOutOrderTask(runningTaskData)

    },
    async moveOrder(){
      this.taskType = 2
      this.isLayerVisible = true
    },
    async outOrder(){
      this.taskType = 1
      console.log(this.list)
      const outorderList = []
      for (let i of this.list){
        for (let j of i){
          if (j.cargoLocationStatus ==1 ){
            outorderList.push(j)
          }
        }
      }
      console.log(this.activeIndex,this.warehouselayerZ)
      if (outorderList.length == 0){
        this.handleChange(this.activeIndex+1)
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cargoNo: null,
        cargoName: null,
        areaId: null,
        roadNo:null,
        roadLine: null,
        warehouse: null,
        palletNo: null,
        cargoLocationStatus: null,
        cargoType: null,
        posiX: null,
        posiY: null,
        posiZ: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(item) {
      console.log(item);
      if(this.taskType == 1){
        this.taskInfo = item
      }
      this.form = item;
      this.update = true;
      this.title = t('component.index.updateTitle');
      // this.reset();
      // const id = row.id || this.ids
      // getCargo(id).then(response => {
      //   this.form = response.data;
      //   this.update = true;
      //   this.title = t('component.index.updateTitle');
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateCargo(this.form).then(response => {
            // this.$modal.msgSuccess(this.$i18n.t('index.success'));
            this.update = false;
            this.handleChange(this.itemIndex);
          });
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // eslint-disable-next-line no-undef
      this.getWarehouseList(warehouseNo)
    },
    getWarehouse1List() {
      listWarehouse(this.warehouseParams).then(response => {
        this.warehouseList = response.rows
      })
    },
    getList(){
      var X = this.warehouselayerX
      var index = 1
      const params = { index, X }
      // 重新获取该层的数据
      listCargo1(params).then(response => {
        this.list = response.rows
        console.log('rows===', this.rows)
        console.log('list===', this.list)
      })
    },
    handleChange(index) {
      this.activeIndex = index
      this.itemIndex  = index
      var X = this.warehouselayerX
      console.log('Y2 ===', X)
      const params = { index, X }
      // 重新获取该层的数据
      getCargoList(params).then(res=>{
        console.log(res);
        this.list = res
      })
      // this.getList()
    },
    getImg(item) {
      const obj = this.imgList.find(e => e.cargoType === item.cargoType)
      return obj.img
    }
  }
}
</script>
<style lang="scss" scoped>
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.content-overlay {
  background: #fff;
  padding: 20px;
}
.ha{
  position:absolute;
  top:396px;
  left: 716px;
}
.box-card {
  .card-label {
    color: rgb(197, 197, 197);
    margin-right: 8px;
    width: 170px;
    display: inline-block;
    margin-bottom: 5px;
  }
}
.info_card{
  background-color: white;
  width: 300px;
  //position: absolute;
}
.tooltip {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #f9f9f9;
  border: 1px solid #ccc;
  padding: 5px;
}


.container {
  padding: 30px;
}

.top {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  border: 1px solid #eee;
  gap: 20px;
  padding: 15px 0;

  .img-item {
    display: flex;
    align-items: center;

    span {
      margin: 0 10px;
    }

    img {
      width: 30px;
    }
  }
}

.content {
  user-select: none;
  -webkit-user-drag: none;
  display: flex;
  gap: 20px;

  .level {
    width: 100px;

    .level-item {
      cursor: pointer;
      height: 60px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #eee;
      margin-bottom: 30px;
    }
    .active {
      background: #0a87ec;
      color: #fff;
    }
  }
  .levelsyn {
    width: 50px;

    .syn-item {
      cursor: pointer;
      height: 60px;
      width: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #eee;
      margin-bottom: 30px;
    }
    .syn {
      background: #7e7e7e;
      color: #fff;
    }
  }

  .out_order {
    animation: glow 800ms ease-out infinite alternate;
    //border-color: #393;
    //box-shadow: 0 0 5px rgba(0,255,0,.2), inset 0 0 5px rgba(0,255,0,.1), 0 2px 0;
    color: #efe;
    outline: none;
  }
  @keyframes glow {
      0% {
      //border-color: #393;
      //box-shadow: 0 0 5px rgba(0,255,0,.2), inset 0 0 5px rgba(0,255,0,.1), 0 2px 0;
        background: red;
      }
      100% {
      //border-color: #6f6;
        //box-shadow: 0 0 20px rgba(0,255,0,.6), inset 0 0 10px rgba(0,255,0,.4), 0 2px 0;
        background: pink;
      }
  }

  .move_orderEnd{
    animation: moveend 800ms ease-out infinite alternate;
    //border-color: #393;
    //box-shadow: 0 0 5px rgba(0,255,0,.2), inset 0 0 5px rgba(0,255,0,.1), 0 2px 0;
    color: #efe;
    outline: none;
  }
  @keyframes moveend {
    0% {
      //border-color: #393;
      //box-shadow: 0 0 5px rgba(0,255,0,.2), inset 0 0 5px rgba(0,255,0,.1), 0 2px 0;
      background: #f9f9f9;
    }
    100% {
      //border-color: #6f6;
      //box-shadow: 0 0 20px rgba(0,255,0,.6), inset 0 0 10px rgba(0,255,0,.4), 0 2px 0;
      background: lightgreen;
    }
  }
  .box {
    // transform: scale(var(--scale, 1)) translate(var(--positionX, 0px), var(--positionY, 0px));
    align-content: flex-start;
    flex: 1;
    overflow: auto;
    .line {
      display: flex;
    }
    .item {
      //transform: scale(var(--scale, 1)) translate(var(--positionX, 0px), var(--positionY, 0px));
      width: 60px;
      flex-shrink: 0;
      height: 35px;
      background: #eee;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 5px 5px 0;
      .roadno {
        font-size: small;
        color: #0A87EC;
      }
      .roadline {
        font-size: small;
        color: #038b09;
      }
      img {
        width: 50%;
        transition: transform 0.3s ease; // 添加过渡效果
      }

      &:hover img {
        transform: scale(1.1); // 鼠标悬停时放大图标
      }
    }

    .full {
      background: red;
    }

    .lock{
      background: yellow;
    }
  }
}
</style>
